import os,sys,datetime,subprocess
#SELECT DBMS_FLASHBACK.GET_SYSTEM_CHANGE_NUMBER SCN FROM DUAL;
def get_datasync_log(log_file):
	with open(log_file, encoding='utf-8') as f:
		data = f.readlines()
		log_loc = data[-1].strip('\n').split('[')[-1].strip(']')
		log_loc_full =  './' + log_file.split('/')[1] + log_loc.split('.')[-1]
		print('log_loc_full: {0}'.format(log_loc_full))
		
		return log_loc_full

def get_scn(log_loc):
	#os.chdir("/migerate/python_LME_gb/python_LME/bin")
	get_scn_cmd = "grep 'Current scn' {0}dss_info_log.log".format(log_loc)
	print('get_scn_cmd: {0}'.format(get_scn_cmd))
	output = subprocess.getoutput(get_scn_cmd)
	scn = str(output.split(':')[-1])
	return scn

def replace_scn(ar_sql, scn_flag, scn_num):
	replace_scn_cmd = "find ./DataSync_dr_evc_mgt/upgrade/ -name '{0}' | xargs sed -i 's/{1}/{2}/g'".format(str(ar_sql), str(scn_flag), str(scn_num))
	print('replace_scn_cmd: {0}'.format(replace_scn_cmd))
	status, output = subprocess.getstatusoutput(replace_scn_cmd)
	if str(status) == '0':
		return True
	else:
		print(status, output)
		return False

def main():
	log_cfg = {
		'scn_mgt_livedb': './DataSync_dr_evc_mgt/evc_mgt_live_cur.log',
		'scn_sys_livedb': './DataSync_dr_evc_mgt/evc_sys_live_cur.log',
		'scn_txn_livedb_cur': './DataSync_dr_evc_txn/evc_txn_live_cur.log',
		'scn_txn_livedb_his_cur': './DataSync_dr_evc_txn/evc_txn_live_his_cur.log'
	}

	ar_sql = {
		'evc_ar_oracle': 'evc_ar_oracle_0730_alldb.sql',
		'evc_ar_gauss': 'evc_ar_gauss.sql'
	}

	replace_scn(ar_sql.get('evc_ar_oracle'), 'scn_mgt_livedb', get_scn(get_datasync_log(log_cfg.get('scn_mgt_livedb'))))
	replace_scn(ar_sql.get('evc_ar_oracle'), 'scn_sys_livedb', get_scn(get_datasync_log(log_cfg.get('scn_sys_livedb'))))
	replace_scn(ar_sql.get('evc_ar_oracle'), 'scn_txn_livedb_cur', get_scn(get_datasync_log(log_cfg.get('scn_txn_livedb_cur'))))
	replace_scn(ar_sql.get('evc_ar_oracle'), 'scn_txn_livedb_his_cur', get_scn(get_datasync_log(log_cfg.get('scn_txn_livedb_his_cur'))))

if __name__ == '__main__':
	time1 = datetime.datetime.now()
	main()
	time2 = datetime.datetime.now()
	print('start time: ', time1)
	print('end time: ', time2)
	print('total time: ', time2 - time1)